package dao

import (
	"errors"
	"gin_zebra/app/dto"
	"gin_zebra/public"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

type User struct {
	Id       int    `json:"id" gorm:"primary_key" description:"自增主键"`
	App      string `json:"-" gorm:"column:app" description:"应用平台"`
	Nickname string `json:"nickname" gorm:"column:nickname" description:"昵称"`
	Username string `json:"username" gorm:"column:username" description:"账号"`
	Password string `json:"-" gorm:"column:password" description:"密码"`
	Salt     string `json:"-" gorm:"column:salt" description:"salt"`
	Phone    string `json:"phone" gorm:"column:phone" description:"手机号"`
	Email    string `json:"email" gorm:"column:email" description:"邮箱"`
	Avatar   string `json:"avatar" gorm:"column:avatar" description:"avatar"`
	Sex      int    `json:"sex" gorm:"column:sex" description:"性别"`
	Memo     string `json:"-" gorm:"column:memo" description:"备注"`
	IsDel    int    `json:"-" gorm:"column:is_del" description:"是否删除"`
	AddTime  int64  `json:"add_time" gorm:"column:add_time" description:"创建时间"`
	ModTime  int64  `json:"mod_time" gorm:"column:mod_time" description:"更新时间"`
}

func (t *User) TableName() string {
	return "user"
}

func (t *User) LoginCheck(ctx *gin.Context, db *gorm.DB, param *dto.UserLoginInput) (*User, error) {
	info, err := t.Find(ctx, db, &User{Username: param.UserName, IsDel: 10})
	if err != nil {
		return nil, errors.New("用户信息不存在")
	}

	saltPwd := public.GenSaltPassword(info.Salt, param.Password)
	if info.Password != saltPwd {
		return nil, errors.New("密码错误， 请重新输入")
	}
	return info, nil
}

func (t *User) Find(ctx *gin.Context, db *gorm.DB, search *User) (*User, error) {
	out := &User{}
	err := db.Where(search).Find(out).Error

	if err != nil {
		return nil, err
	}

	return out, nil
}

func (t *User) Save(ctx *gin.Context, db *gorm.DB) error {
	return db.Save(t).Error
}

/* =================================================================
	注册
 * =================================================================*/
type UserReg struct {
	Id       int    `json:"id" gorm:"primary_key" description:"自增主键"`
	Username string `json:"username" gorm:"column:username" description:"账号"`
	Password string `json:"password" gorm:"column:password" description:"密码"`
	Salt     string `json:"salt" gorm:"column:salt" description:"salt"`
	AddTime  int64  `json:"add_time" gorm:"column:add_time" description:"创建时间"`
	ModTime  int64  `json:"mod_time" gorm:"column:mod_time" description:"更新时间"`
}

func (t *UserReg) TableName() string {
	return "user"
}

func (t *UserReg) Save(ctx *gin.Context, db *gorm.DB) error {
	return db.Save(t).Error
}

func (t *UserReg) Find(ctx *gin.Context, db *gorm.DB, search *UserReg) (*User, error) {
	out := &User{}
	err := db.Where(search).Find(out).Error

	if err != nil {
		return nil, err
	}

	return out, nil
}
